<template>
  <div class="banner-wrapper">
    <Row>
      <Col :span="12"
           style="text-align: left;">
      <h2>{{$t('m.xiāoxítōngzhī')}}</h2>
      </Col>
      <Col :span="12"
           style="text-align: right;">
      <Button type="primary"
              @click="handleAdd">{{$t('m.add')}}</Button>
      </Col>
    </Row>
    <Tabs style="margin-top: 15px;"
          v-model="tab"
          @on-click="handleTab">
      <TabPane :label="this.$t('m.xiǎnshìtōngzhī')"
               name="1">
        <Table ref="table"
               border
               :data="data1"
               :columns="columns"
               :loading="loading">
        </Table>
      </TabPane>
      <TabPane :label="this.$t('m.yǐncángtōngzhī')"
               name="0">
        <Table ref="table"
               border
               :data="data0"
               :columns="columns2"
               :loading="loading">
        </Table>
      </TabPane>
    </Tabs>
    <!--    添加modal-->
    <Modal footer-hide
           v-model="addd"
           title="Add notice">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="80">
        <FormItem :label="this.$t('m.picture')"
                  prop="imgUrl">
          <div class="priview">
            <img :src="formValidate.imgUrl"
                 alt=""
                 class="priview-image">
          </div>
          <Upload ref="upload"
                  :format="['jpg','jpeg','png']"
                  accept="image/jpeg,image/png"
                  action=""
                  :show-upload-list="false"
                  :before-upload="handleBeforeUpload">
            <Button icon="ios-cloud-upload-outline"
                    :loading="btnLoading">{{$t('m.scImg')}}</Button>
          </Upload>
        </FormItem>
        <FormItem :label="this.$t('m.title')"
                  prop="title">
          <Input v-model="formValidate.title"
                 :placeholder="$t('m.qǐngshūrùbiāotí')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.linkurl')"
                  prop="imgUrl">
          <Input v-model="formValidate.imgUrl"
                 :placeholder="$t('m.qǐngshūrùliànjiē')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.shunxu')"
                  prop="linkUrl">
          <Input v-model="formValidate.linkUrl"
                 :placeholder="$t('m.qǐngshūrùshùnxù')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.dlqdId')"
                  prop="shunxu">
          <Input v-model="formValidate.shunxu"
                 number
                 :placeholder="$t('m.qǐngshūrùdǎoliúqúdàoID')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.sfZahnshi')"
                  prop="isShow">
          <RadioGroup v-model="formValidate.isShow">
            <Radio label=1>{{$t('m.zs')}}</Radio>
            <Radio label=0>{{$t('m.nzs')}}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem :label="this.$t('m.dǎkāifāngshì')"
                  prop="openType">
          <RadioGroup v-model="formValidate.openType">
            <Radio label="in">App</Radio>
            <Radio label="out">Web</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem :label="this.$t('m.xiǎnshìpíngtái')"
                  prop="target">
          <RadioGroup v-model="formValidate.target">
            <Radio label="all">{{$t('m.allplat')}}</Radio>
            <Radio label="android">{{$t('m.ānzhuō')}}</Radio>
            <Radio label="ios">{{$t('m.ios')}}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem :label="this.$t('m.remarkCo')"
                  prop="Content">
          <Input v-model="formValidate.Content"
                 type="textarea"
                 :autosize="{minRows: 2,maxRows: 5}"
                 :placeholder="$t('m.qǐngshūrùbèizhù')"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary"
                  @click="handleSubmit()"
                  :loading="loading1">{{$t('m.submit')}}</Button>
          <Button @click="handleReset('formValidate')"
                  style="margin-left: 8px">{{$t('m.recycle')}} </Button>
        </FormItem>
      </Form>
    </Modal>
    <!--    编辑Modal-->
    <Modal footer-hide
           v-model="editM"
           title="Edit notice">
      <Form ref="formValidate"
            :model="editData"
            :rules="ruleEdit"
            :label-width="80">
        <FormItem :label="this.$t('m.picture')"
                  prop="imgUrl">
          <div class="priview">
            <img :src="editData.imgUrl"
                 alt=""
                 class="priview-image">
          </div>
          <Upload ref="upload"
                  :format="['jpg','jpeg','png']"
                  accept="image/jpeg,image/png"
                  action=""
                  :show-upload-list="false"
                  :before-upload="handleBeforeUpload2">
            <Button icon="ios-cloud-upload-outline"
                    :loading="btnLoading">{{$t('m.scImg')}}</Button>
          </Upload>
        </FormItem>
        <FormItem :label="this.$t('m.title')"
                  prop="title">
          <Input v-model="editData.title"
                 :placeholder="$t('m.qǐngshūrùbiāotí')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.linkurl')"
                  prop="imgUrl">
          <Input v-model="editData.imgUrl"
                 :placeholder="$t('m.qǐngshūrùliànjiē')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.shunxu')"
                  prop="linkUrl">
          <Input v-model="editData.linkUrl"
                 :placeholder="$t('m.qǐngshūrùshùnxù')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.dlqdId')"
                  prop="shunxu">
          <Input v-model="editData.sort"
                 number
                 :placeholder="$t('m.qǐngshūrùshùnxù')"></Input>
        </FormItem>
        <FormItem :label="this.$t('m.sfZahnshi')"
                  prop="isShow">
          <RadioGroup v-model="editData.status">
            <Radio label=1>{{$t('m.zs')}}</Radio>
            <Radio label=0>{{$t('m.nzs')}}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem :label="this.$t('m.dǎkāifāngshì')"
                  prop="openType">
          <RadioGroup v-model="editData.openType">
            <Radio label="in">App</Radio>
            <Radio label="out">Web</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem :label="this.$t('m.xiǎnshìpíngtái')"
                  prop="target">
          <RadioGroup v-model="editData.target">
            <Radio label="all">{{$t('m.allplat')}}</Radio>
            <Radio label="android">{{$t('m.ānzhuō')}}</Radio>
            <Radio label="ios">{{$t('m.ios')}}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem :label="this.$t('m.remarkCo')"
                  prop="Content">
          <Input v-model="editData.content"
                 type="textarea"
                 :autosize="{minRows: 2,maxRows: 5}"
                 :placeholder="$t('m.qǐngshūrùbèizhù')"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary"
                  @click="editSubmit()"
                  :loading="loading2">{{$t('m.submit')}}</Button>
          <Button @click="handleReset('formValidate')"
                  style="margin-left: 8px">{{$t('m.recycle')}} </Button>
        </FormItem>
      </Form>
    </Modal>
  </div>

</template>

<script>
import qs from 'qs';

export default {
  name: 'banner',
  data () {
    return {
      loading1: false,
      loading2: false,
      imgs: '',
      btnLoading: false,
      show: this.value,
      imgArr: '',
      form: {},
      editM: false,
      editData: {
        imgUrl: ''
      },
      formValidate: {
        title: '',
        imgUrl: '',
        linkUrl: '',
        shunxu: '',
        target: '',//目标用户
        openType: '',
        isShow: '',
        Content: ''
      },
      ruleValidate: {
        title: [
          { required: true, message: 'The title cannot be empty', trigger: 'blur' }
        ],
        shunxu: [
          { type: 'number', message: 'Number only', trigger: 'change' }
        ],
        isShow: [
          { required: true, message: 'Please select', trigger: 'blur' }
        ],
      },
      ruleEdit: {
        title: [
          { required: true, message: 'The title cannot be empty', trigger: 'blur' }
        ],
        shunxu: [
          { type: 'number', message: 'Number only', trigger: 'change' }
        ],
        isShow: [
          { required: true, message: 'Please select', trigger: 'blur' }
        ],
      },
      addd: false,
      columns: [
        {
          title: this.$t('m.picture'),
          key: 'imgUrl',
          align: 'center',
          render: (h, params) => {
            return h('div', {
              style: {
                paddingTop: '5px',
                paddingBottom: '5px'
              }
            }, [
              h('img', {
                attrs: {
                  src: params.row.imgUrl
                },
                style: {
                  maxHeight: '60px'
                }
              }),
            ]);
          }
        },
        {
          title: this.$t('m.deLinkurl'),
          key: 'linkUrl',
          align: 'center',
          render: (h, params) => {
            const { linkUrl } = params.row;
            return h('a', {
              attrs: {
                href: linkUrl,
                target: '_blank'
              },
              style: {
                color: '#2d8cf0',
                textDecoration: 'underline'
              }
            }, linkUrl);
          }
        },
        {
          title: this.$t('m.deTitle'),
          key: 'title',
          align: 'center'
        },
        {
          title: this.$t('m.showSort'),
          key: 'sort',
          align: 'center'
        },
        {
          title: this.$t('m.type'),
          key: 'openType',
          align: 'center',
        },
        {
          title: this.$t('m.remarkCo'),
          key: 'content',
          align: 'center'
        },
        {
          title: this.$t('m.operate'),
          width: 150,
          align: 'center',
          render: (h, params) => {
            let id = params.row.id;
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '10px'
                },
                on: {
                  click: () => {
                    this.handleEdit(id);
                  }
                }
              }, this.$t('m.edit')),
              h('Poptip', {
                props: {
                  confirm: true,
                  title: this.$t('m.sdList'),
                  placement: 'left',
                  transfer: true
                },
                on: {
                  'on-ok': () => {
                    this.handleDelete(id);
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      // console.log('delete');
                    }
                  }
                }, this.$t('m.delete'))
              ])
            ]);
          }
        }
      ],
      columns2: [
        {
          title: this.$t('m.picture'),
          key: 'imgUrl',
          align: 'center',
          render: (h, params) => {
            return h('div', {
              style: {
                paddingTop: '5px',
                paddingBottom: '5px'
              }
            }, [
              h('img', {
                attrs: {
                  src: params.row.imgUrl
                },
                style: {
                  maxHeight: '60px'
                }
              }),
            ]);
          }
        },
        {
          title: this.$t('m.deLinkurl'),
          key: 'linkUrl',
          align: 'center',
          render: (h, params) => {
            const { linkUrl } = params.row;
            return h('a', {
              attrs: {
                href: linkUrl,
                target: '_blank'
              },
              style: {
                color: '#2d8cf0',
                textDecoration: 'underline'
              }
            }, linkUrl);
          }
        },
        {
          title: this.$t('m.deTitle'),
          key: 'title',
          align: 'center'
        },
        {
          title: this.$t('m.showSort'),
          key: 'sort',
          align: 'center'
        },
        {
          title: this.$t('m.type'),
          key: 'openType',
          align: 'center',
        },
        {
          title: this.$t('m.remarkCo'),
          key: 'content',
          align: 'center'
        },
        {
          title: this.$t('m.operate'),
          width: 150,
          align: 'center',
          render: (h, params) => {
            let id = params.row.id;
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '10px'
                },
                on: {
                  click: () => {
                    this.handleEdit(id);
                  }
                }
              }, this.$t('m.edit')),
              h('Poptip', {
                props: {
                  confirm: true,
                  title: this.$t('m.sdList'),
                  placement: 'left',
                  transfer: true
                },
                on: {
                  'on-ok': () => {
                    this.handleDelete(id);
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      // console.log('delete');
                    }
                  }
                }, this.$t('m.delete'))
              ])
            ]);
          }
        }
      ],
      data1: [],
      data0: [],
      loading: false,
      title: '',
      showModal: false,
      tab: '1',
      type: ''
    }
  },
  created () {
    this.getNoticeList();
    this.getNoticeListN()

  },
  methods: {
    handleBeforeUpload2 (file) {
      const reg = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;

      if (!reg.test(file.type)) return this.$Message.error(this.$t('m.zhǐnéngshàngchuánjpgjpegpnggéshìdetúpiàn'));
      if (this.imgs.length > 1) return this.$Message.error(this.$t('m.zuìduōshàngchuán1zhāngtúpiàn'));
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        let result = e.target.result;
        this.editData.imgUrl = result
      }

      reader.onerror = (e) => {
        this.$Message.error(this.$t('m.túpiànzhuǎnchéngbase64cuòwù'));
      }

      return false;
    },
    handleBeforeUpload (file) {
      const reg = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;

      if (!reg.test(file.type)) return this.$Message.error(this.$t('m.zhǐnéngshàngchuánjpgjpegpnggéshìdetúpiàn'));
      if (this.imgs.length > 1) return this.$Message.error(this.$t('m.zuìduōshàngchuán1zhāngtúpiàn'));
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        let result = e.target.result;
        this.formValidate.imgUrl = result
      }

      reader.onerror = (e) => {
        this.$Message.error(this.$t('m.túpiànzhuǎnchéngbase64cuòwù'));
      }

      return false;
    },
    editSubmit () {
      this.loading2 = true
      this.$http.post('/api/laocai/sys/notice/update', this.editData).then((res) => {
        if (res.body.code == 0) {
          this.loading2 = false
          this.editM = false
          this.getNoticeList()
          this.$Message.success('Success!')
        } else {
          this.loading2 = false
          this.$Message.warning(res.body.message);
        }
        this.loading2 = false
      })
    },
    getNoticeList () {
      var _this = this
      this.$http.get('/api/laocai/sys/notice/list').then((res) => {
        if (res.body.code == 0) {
          if (res.body.result) {
            this.data1 = res.body.result.list
            this.loading = false
          }
        } else {
          this.$Message.success(this.$t('m.errorCode' + res.body.code));
        }
      })
    },
    getNoticeListN () {
      var _this = this
      this.$http.get('/api/laocai/sys/notice/list?status=0').then((res) => {
        if (res.body.code == 0) {
          if (res.body.result) {
            this.data0 = res.body.result.list
            this.loading = false
          }
        } else {
          this.$Message.success(this.$t('m.errorCode' + res.body.code));
        }
      })
    },
    handleSubmit () {
      this.loading1 = true
      this.$http.post('/api/laocai/sys/notice/add', {
        title: this.formValidate.title,
        content: this.formValidate.content,
        imgUrl: this.formValidate.imgUrl,
        linkUrl: this.formValidate.linkUrl,
        openType: this.formValidate.openType,
        sort: this.formValidate.shunxu,
        status: this.formValidate.isShow,
        target: this.formValidate.target,
      }).then((res) => {
        if (res.body.code == 0) {
          this.loading1 = false
          this.addd = false
          this.$Message.success('Success!')
        } else {
          this.loading1 = false
          this.$Message.warning(res.body.message);
        }
        this.loading1 = false
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields();
    },

    getBannerList () {
      this.loading = true;
      this.$http.get('/api/laocai/sys/banner/list').then((res) => {
        if (res.body.code == 0) {
          var _this = this
          res.body.result.list.forEach(function (val, index, val_arr) {
            switch (val_arr[index].status) {
              case 1:
                _this.data1.push(val_arr[index]);
                break;
              case 0:
                _this.data0.push(val_arr[index]);
                // console.log('test2'+JSON.stringify(test2));
                break;
              default:
                break;
            }
          });
          // console.log(res)
          this.loading = false
        } else {
          this.$Message.warning(res.body.message);
        }


      })
    },
    handleTab (name) {
      this.tab = name;
    },
    handleAdd () {
      this.addd = true;
    },
    handleEdit (id) {
      this.editM = true
      console.log(id);
      var url1 = '/api/laocai/sys/notice/info?id=' + id
      this.$http.get(url1).then((res) => {
        console.log(res);
        this.editData = res.body.result
      })
    },
    handleDelete (id) {
      this.$http.post('/api/laocai/sys/notice/update', {
        id: id,
        status: 0
      })
        .then((res) => {
          if (res.body.code == 0) {
            this.$Message.success('删除banner成功');
            this.getBannerList();
            this.getNoticeListN();
          } else {
            this.$Message.warning(res.body.message);
          }
        }, error => {
          console.log(error);
        })
    },
    handleModalCancel (status) {
      this.showModal = false;
    },
    handleModalOk () {
      this.showModal = false;
      this.getBannerList();
    }
  },
}
</script>

<style lang="scss" scoped>
.priview {
  margin-bottom: 10px;
  .priview-image {
    max-height: 60px;
  }
}
.banner-wrapper {
  margin-top: 20px;
  margin: 0px 15px;
  h2 {
    color: #515a6e;
    padding: 0 15px;
    font-size: 16px;
    font-weight: bold;
    line-height: 75px;
    display: inline-block;
  }
}
</style>
